package com.qianbao.qianbaobusiness.ui.mine;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.androidbase.utils.DisplayUtils;
import com.androidbase.utils.RxUtils;
import com.androidbase.utils.ToastUtils;
import com.baseandroid.config.Api;
import com.baseandroid.config.Global;
import com.baseandroid.gaode.GaoDeMap;
import com.baseandroid.mvp.BaseMvpFragment;
import com.baseandroid.retrofit.RxObserver;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qianbao.qianbaobusiness.BuildConfig;
import com.qianbao.qianbaobusiness.R;
import com.qianbao.qianbaobusiness.json.GStoreBean;
import com.qianbao.qianbaobusiness.json.MerchantInfo;
import com.qianbao.qianbaobusiness.json.UnPayShopListBean;
import com.qianbao.qianbaobusiness.ui.deposit.IntroducedServiceActivity;
import com.qianbao.qianbaobusiness.ui.deposit.MyDepositActivity;
import com.qianbao.qianbaobusiness.ui.help.HelpCenterActivity;
import com.qianbao.qianbaobusiness.ui.invoice.ContractListActivity;
import com.qianbao.qianbaobusiness.ui.invoice.ContractStoreListActivity;
import com.qianbao.qianbaobusiness.ui.invoice.GStoreConstant;
import com.qianbao.qianbaobusiness.ui.mine.about.AboutActivity;
import com.qianbao.qianbaobusiness.ui.mine.msgsetting.MessageSettingActivity;
import com.qianbao.qianbaobusiness.ui.mine.personalinfo.PersonalInfoActivity;
import com.qianbao.qianbaobusiness.ui.mine.settlementinfo.SettlementInfoActivity;
import com.qianbao.qianbaobusiness.ui.mine.storeinfo.StoreInfoActivity;
import com.qianbao.qianbaobusiness.ui.qrcode.BindQrCodeActivity;
import com.qianbao.qianbaobusiness.ui.support.customermanager.CustomerManagerActivity;
import com.qianbao.qianbaobusiness.ui.webview.LoanWebviewActivity;
import com.qianbao.qianbaobusiness.ui.webview.SimpleWebViewActivity;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tencent.stat.StatService;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author: Routee
 * @date 2018/6/11
 * @mail wangc4@qianbaocard.com
 * ------------1.本类由Routee开发,阅读、修改时请勿随意修改代码排版格式后提交到git。
 * ------------2.阅读本类时，发现不合理请及时指正.
 * ------------3.如需在本类内部进行修改,请先联系Routee,若未经同意修改此类后造成损失本人概不负责。
 */
public class MineFragment extends BaseMvpFragment<MineView, MinePresenter> implements MineView {
    @BindView(R.id.tv_notify)
    TextView         mTvNotify;
    @BindView(R.id.iv_head)
    RoundedImageView mIvHead;
    @BindView(R.id.tv_name)
    TextView         mTvName;
    @BindView(R.id.tv_position)
    TextView         mTvPosition;
    @BindView(R.id.tv_desc)
    TextView         mTvDesc;
    @BindView(R.id.tv_store_count)
    TextView         mTvStoreCount;
    @BindView(R.id.rl_head)
    RelativeLayout   mRlHead;
    @BindView(R.id.fl_settlement)
    FrameLayout      mFlSettlement;
    @BindView(R.id.fl_repayment)
    FrameLayout      mFlRepayment;
    @BindView(R.id.fl_info)
    FrameLayout      mFlInfo;
    @BindView(R.id.fl_contracts)
    FrameLayout      mFlContracts;
    @BindView(R.id.fl_help)
    FrameLayout      mFlHelp;
    @BindView(R.id.fl_about)
    FrameLayout      mFlAbout;
    @BindView(R.id.fl_setting)
    FrameLayout      mFlSetting;
    @BindView(R.id.fl_qr_code)
    FrameLayout      mFlQrCode;
    @BindView(R.id.fl_deposit)
    FrameLayout      mFlDeposit;
    @BindView(R.id.tv_message)
    TextView         tv_message;
    @BindView(R.id.tv_deal)
    TextView         tv_deal;
    private GStoreBean        mGstoreBean;
    private UnPayShopListBean bean;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_mine;
    }

    @Override
    protected void initInject() {
        getFragmentComponent().inject(this);
    }

    @Override
    protected void setupView(View rootView) {
        mFlQrCode.setVisibility(View.VISIBLE);
        String amount = "";
        if (Global.getShopListInfo().loanInfo != null) {
            amount = Global.getShopListInfo().loanInfo.getAmount();
        }
        try {
            if (Global.getShopListInfo().loanInfo.enableReturn) {
                mFlRepayment.setVisibility(View.VISIBLE);
            } else {
                mFlRepayment.setVisibility(View.GONE);
            }
        } catch (Exception e) {
            mFlRepayment.setVisibility(View.GONE);
        }
        //        mTvNotify.setVisibility(View.VISIBLE);
        //        mFlContracts.setVisibility(View.VISIBLE);
        if (Global.getShopListInfo().merchantList.size() != 0) {
            if ("P900001,P900002,P900003".contains(Global.getShopListInfo().merchantList.get(0).roleCode)) {
                mTvNotify.setVisibility(View.VISIBLE);
                mFlContracts.setVisibility(View.VISIBLE);
            } else {
                mTvNotify.setVisibility(View.GONE);
                mFlContracts.setVisibility(View.GONE);
            }
        }
        if (Global.getUserInfoBean() != null && Global.getUserInfoBean()
                                                        .getUser() != null) {
            mTvName.setText(Global.getUserInfoBean().getUser().getUserName());
            mTvPosition.setText(Global.getUserInfoBean().getUser().getPositionName());
        }
        List<MerchantInfo> list = Global.getShopListInfo().merchantList;
        StringBuilder sb = new StringBuilder();
        if (list.size() > 1) {
            sb.append(list.get(0).merchantName).append("...");
        } else if (list.size() == 1) {
            sb.append(list.get(0).merchantName);
        }
        mTvDesc.setText(sb.toString());
        if (list.size() > 1) {
            mTvStoreCount.setText("等" + list.size() + "家店");
            mTvDesc.setMaxWidth(DisplayUtils.dp2px(140));
        } else {
            mTvStoreCount.setText("");
            mTvDesc.setMaxWidth(DisplayUtils.dp2px(200));
        }
        if (Global.getShopListInfo().merchantList != null && Global.getShopListInfo().merchantList.size() == 0) {
            mFlDeposit.setVisibility(View.GONE);
        }
        getGStoreList();
    }

    private void getGStoreList() {
        getPresenter().getGstoreList();
        getPresenter().getMerchantUnpayDepositInfo(getMerchantNos());
        //        getPresenter().getMerchantDepositInfo(Global.getShopListInfo().getMerchantNos());
    }

    @Override
    protected void setupData(Bundle savedInstanceState) {

    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        String mobile = Global.getUserInfoBean().getUser().getMobile();
        if (BuildConfig.VERSION_NAME.equals("3.0.2") && !Global.getLoginedUserPhone().contains(mobile + "jinjian")) {
            Global.setLoginedUserPhone(mobile + "jinjian");
            showGuideView();
        }
    }

    private void showGuideView() {
        FrameLayout mRootView = getActivity().findViewById(android.R.id.content);
        RelativeLayout mHelpView = (RelativeLayout) LayoutInflater.from(getActivity()).inflate(R.layout.layout_guide_qrcode_bind_jinjian_step1, null);
        mHelpView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
        ViewTreeObserver viewTreeObserver = mFlQrCode.getViewTreeObserver();
        viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            ViewTreeObserver.OnGlobalLayoutListener listener = this;

            @Override
            public void onGlobalLayout() {
                if (viewTreeObserver.isAlive()) {
                    viewTreeObserver.removeOnGlobalLayoutListener(listener);
                }
                Rect rect = new Rect();
                mFlQrCode.getGlobalVisibleRect(rect);
                mFlQrCode.setDrawingCacheEnabled(true);
                mFlQrCode.buildDrawingCache();
                Bitmap bitmap = Bitmap.createBitmap(mFlQrCode.getDrawingCache());
                mFlQrCode.setDrawingCacheEnabled(false);
                //                ImageView imageView = new ImageView(getActivity());
                //                RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(mFlQrCode.getWidth() - 20, mFlQrCode.getHeight());
                //                lp.setMargins(10, rect.top, 0, 0);
                //                imageView.setScaleType(ImageView.ScaleType.CENTER);
                //                imageView.setImageBitmap(bitmap);
                //                imageView.setLayoutParams(lp);
                ImageView ivContent = mHelpView.findViewById(R.id.iv_content);
                RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(mFlQrCode.getWidth() - 20, mFlQrCode.getHeight());
                lp.setMargins(10, 0, 0, DisplayUtils.getHeight() - rect.bottom);

                ivContent.setLayoutParams(lp);
                ivContent.setImageBitmap(bitmap);
                mRootView.addView(mHelpView);

                mHelpView.findViewById(R.id.iv_confirm).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        bitmap.recycle();
                        mRootView.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mRootView.removeView(mHelpView);
                            }
                        }, 2000);
                        gotoQrcode(true);
                    }
                });
            }
        });
    }

    @OnClick({R.id.rl_head, R.id.fl_settlement, R.id.fl_repayment
            , R.id.fl_info, R.id.fl_manager, R.id.fl_contracts
            , R.id.fl_help, R.id.fl_about, R.id.fl_setting
            , R.id.fl_qr_code, R.id.fl_deposit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_head:
                Intent inPersonalInfo = new Intent(getActivity(), PersonalInfoActivity.class);
                getActivity().startActivity(inPersonalInfo);
                if (!BuildConfig.DEBUG) {
                    StatService.trackCustomEvent(Global.getContext(), "3_0_mine_info");
                }
                break;
            case R.id.fl_settlement:
                Intent settlementIntent = new Intent(getActivity(), SettlementInfoActivity.class);
                getActivity().startActivity(settlementIntent);
                if (!BuildConfig.DEBUG) {
                    StatService.trackCustomEvent(Global.getContext(), "3_0_mine_settlement");
                }
                break;
            case R.id.fl_repayment:
                if (Global.mbLocSuccess) {
                    LoanWebviewActivity.gotoLoanWebView(getActivity(), Global.getUserInfoBean()
                                                                               .getLoanAccessToken(), "loan_repay", "还款记录", "personal");
                    if (!BuildConfig.DEBUG) {
                        StatService.trackCustomEvent(Global.getContext(), "3_0_mine_repayment");
                    }
                } else {
                    new RxPermissions(getActivity()).request(Manifest.permission.ACCESS_FINE_LOCATION)
                            .compose(RxUtils.<Boolean>applySchedulersLifeCycle(getMvpView()))
                            .subscribe(new RxObserver<Boolean>() {
                                @Override
                                public void onNext(Boolean granted) {
                                    if (granted) {
                                        GaoDeMap.getInstance().startMap();
                                    } else {
                                        ToastUtils.showShortToast("定位中...");
                                    }
                                }
                            });
                }
                break;
            case R.id.fl_info:
                Intent storeIntent = new Intent(getActivity(), StoreInfoActivity.class);
                getActivity().startActivity(storeIntent);
                if (!BuildConfig.DEBUG) {
                    StatService.trackCustomEvent(Global.getContext(), "3_0_mine_storeinfo");
                }
                break;
            case R.id.fl_contracts:
                if (mGstoreBean == null) {
                    return;
                }
                List<GStoreBean.ResultBean> gStoreList = mGstoreBean.getResult();
                int size = gStoreList == null ? 0 : gStoreList.size();
                if (Global.getShopListInfo().merchantList.size() + size > 1) {
                    Intent contracStoretIntent = new Intent(getActivity(), ContractStoreListActivity.class);
                    getActivity().startActivity(contracStoretIntent);
                } else {
                    Intent contractIntent = new Intent(getActivity(), ContractListActivity.class);
                    getActivity().startActivity(contractIntent);
                }
                if (!BuildConfig.DEBUG) {
                    StatService.trackCustomEvent(Global.getContext(), "3_0_mine_contract");
                }
                break;
            case R.id.fl_manager:
                Intent manager = new Intent(getActivity(), CustomerManagerActivity.class);
                getActivity().startActivity(manager);
                if (!BuildConfig.DEBUG) {
                    StatService.trackCustomEvent(Global.getContext(), "3_0_mine_manager");
                }
                break;
            case R.id.fl_help:
                Intent helpIntent = new Intent(getActivity(), HelpCenterActivity.class);
                helpIntent.putExtra("sceneId", "2");
                getActivity().startActivity(helpIntent);
                if (!BuildConfig.DEBUG) {
                    StatService.trackCustomEvent(Global.getContext(), "3_0_mine_help");
                }
                break;
            case R.id.fl_setting:
                Intent inSetting = new Intent(getActivity(), MessageSettingActivity.class);
                getActivity().startActivity(inSetting);
                if (!BuildConfig.DEBUG) {
                    StatService.trackCustomEvent(Global.getContext(), "3_0_mine_setting");
                }
                break;
            case R.id.fl_about:
                Intent inAbout = new Intent(getContext(), AboutActivity.class);
                getContext().startActivity(inAbout);
                if (!BuildConfig.DEBUG) {
                    StatService.trackCustomEvent(Global.getContext(), "3_0_mine_about");
                }
                break;
            case R.id.fl_qr_code:
                gotoQrcode(false);
                break;
            case R.id.fl_deposit:
                if ((bean != null && bean.getMerchantWaitPayInfo() != null)) {
                    if (Global.getShopListInfo().merchantList.size() > 1) {  //当前商家名下店铺数量大于1
                        Intent intent = new Intent(getActivity(), MyDepositActivity.class);
                        intent.putExtra("bean", bean);
                        startActivity(intent);
                    } else if (bean.getMerchantWaitPayInfo().get(0).getPayCount().equals("0")
                                       && bean.getMerchantWaitPayInfo().get(0).getReturnPayCount().equals("0")
                                       && bean.getMerchantWaitPayInfo().get(0).getWaitPayCount().equals("0")) {  //当前商家名下店铺小于1，跳转到H5 deposit
                        Intent intent = new Intent(getActivity(), IntroducedServiceActivity.class);
                        startActivity(intent);
                    } else {
                        Intent intent = new Intent(getActivity(), SimpleWebViewActivity.class);
                        intent.putExtra(SimpleWebViewActivity.WEBVIEW_TITLE, "缴纳押金");
                        intent.putExtra(SimpleWebViewActivity.WEBVIEW_URL, Api.depositH5Url + "?merchantNo=" +
                                                                                   Global.getShopListInfo().merchantList.get(0).merchantNo + "&mobile=" +
                                                                                   Global.getShopListInfo().merchantList.get(0).managerMobile);
                        intent.putExtra(SimpleWebViewActivity.WEBVIEW_INIT_QBPAY, true);
                        startActivity(intent);
                    }
                } else {
                    Intent intent = new Intent(getActivity(), IntroducedServiceActivity.class);
                    startActivity(intent);
                }
                break;
            default:
                break;
        }
    }

    private void gotoQrcode(boolean b) {
        Intent qrIntent = new Intent(getActivity(), BindQrCodeActivity.class);
        qrIntent.putExtra("showGuide", b);
        getActivity().startActivity(qrIntent);
    }

    @Override
    public void getGstoreListSuccess(List<GStoreBean.ResultBean> result) {
        mGstoreBean = new GStoreBean();
        mGstoreBean.setResult(result);
        GStoreConstant.setmGStoreBean(mGstoreBean);
        resetContractView();
    }

    @Override
    public void getMerchantUnpaySuccess(UnPayShopListBean result) {
        bean = result;
        tv_deal.setVisibility(TextUtils.equals(result.getTotalWaitPay(), "0") ? View.INVISIBLE : View.VISIBLE);
        tv_message.setText(TextUtils.equals(result.getTotalWaitPay(), "0") ? "" : "您有" + bean.getTotalWaitPay() + "个任务需要处理");
    }

    private void resetContractView() {
        if (mGstoreBean.getResult().size() > 0) {
            mFlContracts.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        getPresenter().getMerchantUnpayDepositInfo(getMerchantNos());
    }

    private String getMerchantNos() {
        String merchantNos = "";
        for (MerchantInfo merchantInfo : Global.getShopListInfo().merchantList) {
            if (TextUtils.isEmpty(merchantNos)) {
                merchantNos = merchantInfo.merchantNo;
            } else {
                merchantNos = merchantNos + "," + merchantInfo.merchantNo;
            }
        }
        return merchantNos;
    }
}
